package com.airline.controller;

import com.airline.dto.ApiResponse;
import com.airline.dto.BookingRequest;
import com.airline.dto.StatusUpdateRequest;
import com.airline.entity.Booking;
import com.airline.service.BookingService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/bookings")
@RequiredArgsConstructor
public class BookingController {
    private final BookingService bookingService;

    @PostMapping
    public ApiResponse<Booking> createBooking(@RequestBody BookingRequest request) {
        try {
            Booking booking = bookingService.createBooking(
                    request.getUserId(),
                    request.getFlightId(),
                    request.getPassengerName(),
                    request.getSeatClass()
            );
            return ApiResponse.success("预订成功", booking);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/user/{userId}")
    public ApiResponse<List<Booking>> getUserBookings(@PathVariable Long userId) {
        List<Booking> bookings = bookingService.getUserBookings(userId);
        return ApiResponse.success("查询成功", bookings);
    }

    @GetMapping("/{id}")
    public ApiResponse<Booking> getBookingById(@PathVariable Long id) {
        Optional<Booking> booking = bookingService.getBookingById(id);
        return booking.map(b -> ApiResponse.success("查询成功", b))
                .orElse(ApiResponse.error("预订不存在"));
    }

    @GetMapping
    public ApiResponse<List<Booking>> getAllBookings() {
        try {
            List<Booking> bookings = bookingService.getAllBookings();
            return ApiResponse.success("获取预订列表成功", bookings);
        } catch (Exception e) {
            return ApiResponse.error("获取预订列表失败: " + e.getMessage());
        }
    }

    // 修复：调用3参数的 updateBookingStatus 方法
    @PutMapping("/{id}/status")
    public ApiResponse<Booking> updateBookingStatus(
            @PathVariable Long id,
            @RequestBody StatusUpdateRequest request,
            @RequestHeader("User-Id") Long currentUserId) {

        try {
            // 修复：调用3参数方法，传递 currentUserId
            Booking updatedBooking = bookingService.updateBookingStatus(id, request.getStatus(), currentUserId);
            return ApiResponse.success("状态更新成功", updatedBooking);
        } catch (Exception e) {
            return ApiResponse.error("状态更新失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public ApiResponse<Booking> updateBooking(@PathVariable Long id, @RequestBody Booking bookingDetails) {
        try {
            return ApiResponse.success("预订更新成功（待实现完整逻辑）", null);
        } catch (Exception e) {
            return ApiResponse.error("预订更新失败: " + e.getMessage());
        }
    }
}